package com.ty.paypal.service.plan;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.paypal.http.HttpResponse;
import com.paypal.orders.ApplicationContext;
import com.paypal.orders.Name;
import com.paypal.orders.Payer;
import com.paypal.orders.PaymentMethod;
import com.ty.paypal.core.Subscriptions;
import com.ty.paypal.core.request.SubscriptionsCreateRequest;
import com.ty.paypal.core.request.body.SubscriptionsRequest;
import com.ty.paypal.service.PayPalClient;

/**
 * 使用订阅
* @author ty
* @createDate 创建时间：2020年2月22日 下午2:55:30
**/
public class UseSubscriptions extends PayPalClient{
	
	public HttpResponse<Subscriptions> use(String planId) throws IOException {
		SubscriptionsCreateRequest request = new SubscriptionsCreateRequest();
		request.requestBody(buildRequestBody(planId));
		HttpResponse<Subscriptions> response = client().execute(request);
		System.out.println(response.result());
		return response;
	}
	
  public SubscriptionsRequest buildRequestBody(String planId) {
	  SubscriptionsRequest body = new SubscriptionsRequest();
	  body.setPlanId(planId);
	  body.setStartTime(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(new Date()));
	  body.setSubscriber(new Payer()
			  .name(new Name().givenName("tang").surname("ai"))
			  .email("tang430524@163.com"));
	  
	  ApplicationContext applicationContext = new ApplicationContext();
	  applicationContext.brandName("共享充电").locale("en-US").shippingPreference("SET_PROVIDED_ADDRESS").userAction("SUBSCRIBE_NOW")
	  	.paymentMethod(new PaymentMethod().payerSelected("PAYPAL").payeePreferred("IMMEDIATE_PAYMENT_REQUIRED"))
	  	.returnUrl("https://example.com/returnUrl")
	  	.cancelUrl("https://example.com/cancelUrl");
	  body.setApplicationContext( applicationContext );
	  return body;
  }
  
  public static void main(String[] args) {
	try {
//		System.out.println(new CreatePlans().authorizationString());
		System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(new Date()));
		new UseSubscriptions().use("P-60161973TV278715WLZIPBDQ");
	} catch (Exception e) {
		e.printStackTrace();
	}
}
}
